package com.learn.training.multithread.chapter6.minchapter2.demo1;

public class Counter {
    public static final Object lock1 = new Object();
    public static final Object lock2 = new Object();
    private int value = 0;
    private int another = 0;

    public void add(int m) {
        synchronized (lock1) {//获得lock1的锁
            System.out.println(Thread.currentThread().getName() + "  add lock1 : " + lock1.toString());
            this.value += m;
            synchronized (lock2) {//获得lock2的锁
                System.out.println(Thread.currentThread().getName() + "  add lock2 : " + lock2.toString());
                this.another += m;
            }//释放lock2的锁
        }//释放lock1的锁
    }

    /**
     * 死锁 示例
     * 线程1获得lock1的锁，线程2获得lock2的锁
     * 线程1需要获得lock2的锁，线程2需要获得lock1的锁
     * 线程1和线程2都无法获得对方的锁，从而产生死锁
     * @param m
     */
//    public void dec(int m){
//        synchronized (lock2){//获得lock2的锁
//            System.out.println(Thread.currentThread().getName() + "  dec lock2 : " + lock1.toString());
//            this.value -= m;
//            synchronized (lock1) {//获得lock1的锁
//                System.out.println(Thread.currentThread().getName() + "dec lock1 : " + lock2.toString());
//                this.another -= m;
//            }//释放lock1的锁
//        }//释放lock2的锁
//    }

    /**
     * 解决死锁的方法
     * @param m
     */
    public void dec(int m){
        synchronized (lock1){//获得lock2的锁
            System.out.println(Thread.currentThread().getName() + "  dec lock1 : " + lock1.toString());
            this.value -= m;
            synchronized (lock2) {//获得lock1的锁
                System.out.println(Thread.currentThread().getName() + "  dec lock2 : " + lock2.toString());
                this.another -= m;
            }//释放lock1的锁
        }//释放lock2的锁
    }
}
